package com.leonyr.smartipaddemo.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.leonyr.smartipaddemo.InitApplication;
import com.leonyr.smartipaddemo.R;
import com.leonyr.smartipaddemo.bean.PicItem;

import java.util.List;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.VH> implements View.OnClickListener {
    private List<PicItem> list;
    private OnItemClickListener listener;

    public ImageAdapter(List<PicItem> list, OnItemClickListener listener) {
        this.list = list;
        this.listener = listener;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_grid_view, parent, false);
        return new VH(v);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        if (list.get(position).isSelected()) {
            holder.rl_bg_iv.setBackgroundColor(InitApplication.getContext().getResources().getColor(R.color.white));
        } else {
            holder.rl_bg_iv.setBackgroundColor(InitApplication.getContext().getResources().getColor(R.color.bg_cro_graphic));
        }
        holder.iv_image.setImageBitmap(list.get(position).getBitmap());
        holder.itemView.setTag(position);
        holder.itemView.setOnClickListener(ImageAdapter.this);
    }

    @Override
    public int getItemCount() {
        if (list == null || list.size() == 0) return 0;
        Log.e("Size", "size " + list.size());
        return list.size();
    }

    @Override
    public void onClick(View view) {
        if (listener != null) {
            int pos = (int) view.getTag();
            listener.onItemClick(pos);
        }
    }

    //② 创建ViewHolder
    public class VH extends RecyclerView.ViewHolder {
        public ImageView iv_image;
        public RelativeLayout rl_bg_iv;

        public VH(View v) {
            super(v);
            this.iv_image = v.findViewById(R.id.iv_image);
            rl_bg_iv = v.findViewById(R.id.rl_bg_iv);
            v.findViewById(R.id.iv_state).setVisibility(View.GONE);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int pos);
    }
}
